package models.helpers;

import dao.common.UserManager;
import dao.hibernate.UserManagerHB;
import models.exceptions.CreateEntityException;
import models.exceptions.GetEntityException;
import models.shop.User;
import play.mvc.Scope;

import java.io.IOException;

public class UserHelper {
    private static UserManager userManager = new UserManagerHB();

    public static User getUser(Scope.Session session) throws GetEntityException, CreateEntityException, IOException {
        User user = null;
        if (isAuthenticated(session)) {
            String userName = session.get("username");
            user = userManager.getByEmail(userName);
            if (user == null) {
                logOut(session);
                user = userManager.getAnonymousUser(session.getId());
            }
        } else {
            user = userManager.getAnonymousUser(session.getId());
        }
        return user;
    }

    private static void logOut(Scope.Session session) {
        session.remove("username");
    }

    public static boolean isAuthenticated(Scope.Session session) {
        return session.contains("username");
    }
}
